package com.junxian.springboot03.common;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * 事务测试
 */
public class TXTest {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.31.90", 6379);
        jedis.auth("123456");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "sunjunxian");

        //开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();

        try{
            multi.set("user1", result);
            multi.set("user2", result);
            //执行事务的任务
            multi.exec();
        }catch (Exception e){
            //放弃事务
            multi.discard();
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }
    }

    /**
     * 测试运行异常
     */
    @Test
    public void testTx(){
        Jedis jedis = new Jedis("192.168.31.90", 6379);
        jedis.auth("123456");
        jedis.flushDB();//清空数据库信息

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "sunjunxian");

        //开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();
//        jedis.watch("user1");
        try{
            multi.set("user1", result);
            multi.set("user2", result);
            int i = 1/0;//代码抛出异常，执行失败
            //执行事务的任务
            multi.exec();
        }catch (Exception e){
            //放弃事务
            multi.discard();
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }
    }
}
